<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="边坡名称" prop="slopeName">
        <el-select v-model="queryParams.slopeName" placeholder="请选择边坡名称" clearable style="width: 200px">
          <el-option
              v-for="dict in slopeCodeList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="监测类型" prop="monitoringType">
        <el-input
          v-model="queryParams.monitoringType"
          placeholder="请输入监测类型"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['slope.warning:threshold:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['slope.warning:threshold:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['slope.warning:threshold:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['slope.warning:threshold:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table scrollbar-always-on v-loading="loading" :data="thresholdList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="边坡名称" fixed="left" align="center" prop="slopeName" width="280px">
        <template #default="scope">
          <dict-tag :options="slopeCodeList" :value="scope.row.slopeName"/>
        </template>
      </el-table-column>
      <el-table-column label="测点编号" fixed="left" align="center" prop="pointNumber" width="280px">
        <template #default="scope">
          <dict-tag :options="monitorIds" :value="scope.row.pointNumber"/>
        </template>
      </el-table-column>
      <el-table-column label="监测类型" align="center" prop="monitoringType" width="100px">
        <template #default="scope">
          <dict-tag :options="monitor_type" :value="scope.row.monitoringType"/>
        </template>
      </el-table-column>
      <el-table-column label="监测内容" align="center" prop="monitoringContent" width="140px"/>
      <el-table-column label="累计值" align="center" prop="cumulativeValue"/>
      <el-table-column label="累计数据单位" align="center" prop="dataUnit" width="100px">
        <template #default="scope">
          <dict-tag :options="data_unit" :value="scope.row.dataUnit"/>
        </template>
      </el-table-column>
      <el-table-column label="变化速率" align="center" prop="changeRate" />
      <el-table-column label="变化速率数据单位" align="center" prop="changeRateUnit" width="100px">
        <template #default="scope">
          <dict-tag :options="change_rate_unit" :value="scope.row.changeRateUnit"/>
        </template>
      </el-table-column>
      <el-table-column label="预警范围" fixed="right" width="200px">
        <template #default="scope">
          <el-tooltip trigger="click" placement="top" effect="light">
            <template #content>
              <div>
                <div style="margin-bottom: 6px; font-size: 15px; color: #666;">
                  <strong>预警规则说明</strong>
                </div>
                <div style="margin-bottom: 6px; font-size: 12px; color: #666;">
                  <div>预警单控为任意一个监测值超出范围</div>
                  <div v-if="scope.row.monitoringType !== '支挡结构物倾斜' && scope.row.monitoringType !== '降雨量'">
                    双控为两个监测值均超出范围
                  </div>
                </div>
                <table style="border-collapse: collapse; margin-top: 5px;">
                  <thead>
                  <tr>
                    <th style="border: 1px solid #ccc; padding: 4px;">颜色</th>
                    <th style="border: 1px solid #ccc; padding: 4px;">单控(75%,85%,100%)</th>
                    <th v-if="scope.row.monitoringType !== '支挡结构物倾斜' && scope.row.monitoringType !== '降雨量'" style="border: 1px solid #ccc; padding: 4px;">双控(60%,70%,85%,100%)</th>
                  </tr>
                  </thead>
                  <tbody>
                  <tr>
                    <td style="border: 1px solid #ccc; padding: 4px;">蓝色</td>
                    <td style="border: 1px solid #ccc; padding: 4px;">
                      累计值 > {{ (scope.row.cumulativeValue * 0.75).toFixed(2) }}{{scope.row.dataUnit}}<br/>
                      或 变化速率 > {{ (scope.row.changeRate * 0.75).toFixed(2) }}{{scope.row.dataUnit}}
                    </td>
                    <td v-if="scope.row.monitoringType !== '支挡结构物倾斜' && scope.row.monitoringType !== '降雨量'" style="border: 1px solid #ccc; padding: 4px;">
                      累计值 > {{ (scope.row.cumulativeValue * 0.6).toFixed(2) }}{{scope.row.dataUnit}}<br/>
                      且 变化速率 > {{ (scope.row.changeRate * 0.6).toFixed(2) }}{{scope.row.dataUnit}}
                    </td>
                  </tr>
                  <tr>
                    <td style="border: 1px solid #ccc; padding: 4px;">黄色</td>
                    <td style="border: 1px solid #ccc; padding: 4px;">
                      累计值 > {{ (scope.row.cumulativeValue * 0.85).toFixed(2) }}{{scope.row.dataUnit}}<br/>
                      或 变化速率 > {{ (scope.row.changeRate * 0.85).toFixed(2) }}{{scope.row.dataUnit}}
                    </td>
                    <td v-if="scope.row.monitoringType !== '支挡结构物倾斜' && scope.row.monitoringType !== '降雨量'" style="border: 1px solid #ccc; padding: 4px;">
                      累计值 > {{ (scope.row.cumulativeValue * 0.7).toFixed(2) }}{{scope.row.dataUnit}}<br/>
                      且 变化速率 > {{ (scope.row.changeRate * 0.7).toFixed(2) }}{{scope.row.dataUnit}}
                    </td>
                  </tr>
                  <tr>
                    <td style="border: 1px solid #ccc; padding: 4px;">橙色</td>
                    <td style="border: 1px solid #ccc; padding: 4px;">
                      累计值 > {{ (scope.row.cumulativeValue * 1.0).toFixed(2) }}{{scope.row.dataUnit}}<br/>
                      或 变化速率 > {{ (scope.row.changeRate * 1.0).toFixed(2) }}{{scope.row.dataUnit}}
                    </td>
                    <td v-if="scope.row.monitoringType !== '支挡结构物倾斜' && scope.row.monitoringType !== '降雨量'" style="border: 1px solid #ccc; padding: 4px;">
                      累计值 > {{ (scope.row.cumulativeValue * 0.85).toFixed(2) }}{{scope.row.dataUnit}}<br/>
                      且 变化速率 > {{ (scope.row.changeRate * 0.85).toFixed(2) }}{{scope.row.dataUnit}}
                    </td>
                  </tr>
                  <tr>
                    <td style="border: 1px solid #ccc; padding: 4px;">红色</td>
                    <td style="border: 1px solid #ccc; padding: 4px;">—</td>
                    <td v-if="scope.row.monitoringType !== '支挡结构物倾斜' && scope.row.monitoringType !== '降雨量'" style="border: 1px solid #ccc; padding: 4px;">
                      累计值 > {{ (scope.row.cumulativeValue * 1.0).toFixed(2) }}{{scope.row.dataUnit}}<br/>
                      且 变化速率 > {{ (scope.row.changeRate * 1.0).toFixed(2) }}{{scope.row.dataUnit}}
                    </td>
                  </tr>
                  </tbody>
                </table>
              </div>
            </template>
            <span style="cursor: pointer; color: #409EFF;">点击查看预警范围</span>
          </el-tooltip>
        </template>
      </el-table-column>


      <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['slope.warning:threshold:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['slope.warning:threshold:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改预警阈值对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="thresholdRef" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="边坡名称" prop="slopeName">
          <el-select v-model="form.slopeName" placeholder="请选择边坡名称" clearable style="width: 50%">
            <el-option
                v-for="dict in slopeCodeList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="测点编号" prop="pointNumber">
          <el-select v-model="form.pointNumber" placeholder="请选择测点编号" clearable style="width: 50%">
            <el-option
                v-for="dict in monitorIds"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="监测类型" prop="monitoringType">
          <el-select v-model="form.monitoringType" placeholder="请选择监测类型" clearable style="width: 50%">
            <el-option
                v-for="dict in monitor_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="监测内容">
          <el-input v-model="form.monitoringContent" placeholder="请输入监测内容"/>
        </el-form-item>
        <el-form-item label="累计值" prop="cumulativeValue">
          <el-input v-model="form.cumulativeValue" placeholder="请输入累计值" />
        </el-form-item>
        <el-form-item label="累计数据单位" prop="dataUnit">
          <el-select v-model="form.dataUnit" placeholder="请选择数据单位" clearable style="width: 200px">
            <el-option
                v-for="dict in data_unit"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="变化速率" prop="changeRate">
          <el-input v-model="form.changeRate" placeholder="请输入变化速率" />
        </el-form-item>
        <el-form-item label="变化速率数据单位" prop="dataUnit">
          <el-select v-model="form.changeRateUnit" placeholder="请选择数据单位" clearable style="width: 200px">
            <el-option
                v-for="dict in change_rate_unit"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="管养单位" prop="deptId">
          <el-select v-model="form.deptId" placeholder="请选择管养单位" clearable style="width: 200px">
            <el-option
                v-for="dict in sys_dept_list"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Threshold">
import { listThreshold, getThreshold, delThreshold, addThreshold, updateThreshold } from "@/api/slope/warning/threshold";
import {listSlopeCode} from "@/api/slope/info/info.js";
import {listMonitorPoints} from "@/api/slope/monitorPoints/monitorpoints.js";

const { proxy } = getCurrentInstance();
const { sys_dept_list,monitor_type, data_unit, change_rate_unit } = proxy.useDict('sys_dept_list','monitor_type', 'data_unit', 'change_rate_unit');

const monitorIds = ref([])
const slopeCodeList = ref([])
const thresholdList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    slopeName: null,
    monitoringType: null,
  },
  rules: {
    slopeName: [
      { required: true, message: "边坡名称不能为空", trigger: "blur" }
    ],
    pointNumber: [
      { required: true, message: "测点编号不能为空", trigger: "blur" }
    ],
    monitoringType: [
      { required: true, message: "监测类型不能为空", trigger: "blur" }
    ],
    monitoringContent: [
      { required: true, message: "监测内容不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询预警阈值列表 */
function getList() {
  loading.value = true;
  listMonitorPoints().then(response => {
    monitorIds.value = Object.entries(response).map(([key, value]) => ({
      label: key,
      value: value
    }))
  })
  listSlopeCode().then(response => {
    // 假设 response 是一个普通的对象
    slopeCodeList.value = Object.entries(response).map(([key, value]) => ({
      label: key,
      value: key
    }))
  })
  listThreshold(queryParams.value).then(response => {
    thresholdList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    slopeName: null,
    pointNumber: null,
    monitoringType: null,
    monitoringContent: null,
    cumulativeValue: null,
    changeRate: null,
    blueSingle: null,
    blueDouble: null,
    yellowSingle: null,
    yellowDouble: null,
    orangeSingle: null,
    orangeDouble: null,
    redSingle: null,
    redDouble: null,
    deptId: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null
  };
  proxy.resetForm("thresholdRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加预警阈值";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getThreshold(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改预警阈值";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["thresholdRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateThreshold(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addThreshold(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除预警阈值编号为"' + _ids + '"的数据项？').then(function() {
    return delThreshold(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('slope.warning/threshold/export', {
    ...queryParams.value
  }, `threshold_${new Date().getTime()}.xlsx`)
}

getList();
</script>
